import axios from 'axios'
import qs from 'qs'
import useUserInfoStore from '@/stores/userinfo'
import useAppStatusStore from '@/stores/appStatus'
import { ElMessage } from 'element-plus'
import netSetting from '@/configs/netSetting'
import pageRouter from '@/router'
const { baseURL, requestTimeout, contentType } = netSetting

const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: { 'Content-Type': contentType }
})

instance.interceptors.request.use(
  (config) => {
    const userinfoStore = useUserInfoStore() // 用户信息store
    // 加入验证
    config.headers['Authorization'] = userinfoStore.token || ''
    if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    const { data } = response
    // console.log(data)
    if (data.success) {
      return Promise.resolve(data)
    } else {
      // 提示请求错误
      ElMessage.error({
        message: data.code + ': ' + data.message,
      })
      if (data.code === 4010 || data.code === 4020) {  // 登录已过期或者未登录
        // 检查是否位于首页
        if(pageRouter.currentRoute.value.fullPath !== "/") {
          // console.log('不位于首页')
          pageRouter.push({ path: '/', name: 'home'})
        } else {
          const appStatusStore = useAppStatusStore()  // 修改状态，弹窗
          appStatusStore.showLogin = true
        }
      }
      return Promise.reject(data.msg)
    }
  },
  (error) => {
    let rejectData = error
    if (error.response) {
      rejectData = error.response.data
      const errorData = error.response.data
      // 登录已过期或者未登录
      if (errorData) {
        if (errorData.code === 4010 || errorData.code === 4020) {
          // 检查是否位于首页
          if(pageRouter.currentRoute.value.fullPath !== "/") {
            // console.log('不位于首页')
            pageRouter.push({ path: '/', name: 'home'})
          } else {
            const appStatusStore = useAppStatusStore()  // 修改状态，弹窗
            appStatusStore.showLogin = true
          }
        } else {
          ElMessage.error({
            message: errorData.code + '错误:' + errorData.message,
          })
        }
      }
    } else {      
      let tipMsg = '网络请求失败，未知的异常。'
      if (error.message === 'Network Error') {
        tipMsg = '服务器错误，请求失败了...'
      }
      if (error.message.includes('timeout')) {
        tipMsg = '请求服务器超时...'
      }
      // 提示网络请求失败
      ElMessage.warning({ message: tipMsg })
    }
    return Promise.reject(rejectData)
  }
)
export default instance;
